<template>
  <div class="_wz_trainingRecords">
    <Card dis-hover :bordered="true">
      <template #title>搜索</template>
      <Form ref="formSearch" :model="formDataSearch" label-position="right" :label-width="100" inline>

        <FormItem label="培训名称">
          <i-input v-model="formDataSearch.planName" placeholder="请输入培训名称" clearable />
        </FormItem>
        <FormItem label="培训方向">
          <i-select v-model="formDataSearch.planDirection" filterable placeholder="请选择培训方向" clearable>
            <Option v-for="item in trainingDirectionList" :key="item.value" :value="item.code">{{ item.value }}</Option>
          </i-select>
        </FormItem>
        <FormItem label="完成状态">
          <i-select v-model="formDataSearch.finishState" filterable placeholder="请选择完成状态" clearable>
            <Option value="0">未开始</Option>
            <Option value="1">已完成</Option>
            <Option value="2">进行中</Option>
          </i-select>
        </FormItem>

        <FormItem label="经营企业">
          <i-input v-model="formDataSearch.deptName" placeholder="请输入经营企业" clearable />
        </FormItem>
        <FormItem label="培训日期">
          <DatePicker type="month" v-model="formDataSearch.createDate" show-week-numbers placeholder="请选择培训日期" @on-change="formDataSearch.createDate = $event"/>
        </FormItem>
        <FormItem>
          <Button type="primary" @click="searchSubmit">搜索</Button>
        </FormItem>
      </Form>
    </Card>
    <Card dis-hover :bordered="true" style="height: 100%;overflow: hidden;margin: 10px 0 0;">
      <template #title>列表</template>
      <template #extra>
        <Button type="primary" @click="exportData" style="position: relative;top: -8px;">导出</Button>
      </template>
      <wzTbale ref="wzTbale" :tableData="tableData"></wzTbale>
    </Card>



    <Drawer :title="formTitle" v-model="formOperation" width="1200" :draggable="true">
        <trainingRecordsDetails v-if="formOperation" :selectData="selectData"></trainingRecordsDetails>
    </Drawer>


    <Drawer :title="formTitle" v-model="formOperation1" width="1200" :draggable="true">
        <PrintLearning v-if="formOperation1"  :materialData="materialData" :active="selectData" ></PrintLearning>
    </Drawer>

  </div>
</template>
<script>


import {resolveComponent,getCurrentInstance,inject,nextTick,reactive, toRefs,toRef,onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted, ref,defineComponent,toRaw,watch} from 'vue'
import { useRouter,useRoute } from "vue-router";

import { useMainStore } from '../../store'  //pinia 使用 类似 vuex
import { storeToRefs } from 'pinia'//pinia 使用 类似 vuex
const mainStore = useMainStore() //pinia 使用 类似 vuex


import wzTbale from "../../components/table/index.vue";
import {systemDictList} from "../../util/commonInterfaces.js";//字典接口
import trainingRecordsDetails from "../basic/trainingRecordsDetails.vue";//培训列表
import PrintLearning from "../basic/PrintLearning.vue";//培训详情

//reactive
export default defineComponent({
  name: 'trainingRecords',//组件名称
  props: ['trainCoursePlanType'],//接收来自父组件的数据
  components: {
    wzTbale,//表格
    trainingRecordsDetails,//培训列表
    PrintLearning,//培训详情
  },//组件引用
  setup (props,context) {


    const apiUrl = inject('$apiUrl'); // 变量全局化 后台地址
    const $axios = inject('$axiosInterceptor');// 变量全局化 axios
    const $ViewUIPlus = inject('$ViewUIPlus');//引用全局组件
    const router = useRouter();//路由跳转使用
    const $common = inject('$common');//自己封装的方法

    // 用于获取$refs
    const wzTbale = ref();


    const state = reactive({
      formDataSearch:{
        trainCoursePlanType:props.trainCoursePlanType,
        createDate:$common.timeFormatting(new Date(),'yyyy-MM')
      },//搜索条件

      tableData: {
        url: apiUrl.educateTrainPlanTrainCoursePlanPageList,//请求地址
        method: 'post',//请求方式
        where: {
          trainCoursePlanType:props.trainCoursePlanType,
          createDate:$common.timeFormatting(new Date(),'yyyy-MM')
        },//搜索条件
        height: '100%',//表格高度 auto
        page: true,//分页是否使用
        columns: [//表头数据
          {type: 'index', width: 70, align: 'center', title: '序号'},


          {title: '经营企业', minWidth: 210, key: 'deptName',tooltip:true,resizable: true,},
          {
            title: '培训周期', minWidth: 120,tooltip:true,resizable: true, render: (h, params) => {
              return h('span', params.row.trainCoursePlanCreateYear + '年' + params.row.trainCoursePlanCreateMonth + '月')
            }
          },
          { title: '培训课程', minWidth: 200, key: 'trainCoursePlanName',tooltip:true,resizable: true },
          { title: '培训方向', minWidth: 100, key: 'trainCoursePlanDirectionName' ,tooltip:true,resizable: true},
          {
            title: '发布状态', minWidth: 140,tooltip:true,resizable: true, render: (h, params) => {
              //  0：未开始，1：已完成，-1：进行中
              if (params.row.trainCoursePlanRelease == 1) {
                return h(resolveComponent('Tag'), {type: 'dot',color: 'success'}, '已发布');
              } else if (params.row.trainCoursePlanRelease == 2) {
                return h(resolveComponent('Tag'), {type: 'dot',color: 'primary'}, '发布中');
              } else if (params.row.trainCoursePlanRelease == 0) {
                return h(resolveComponent('Tag'), {type: 'dot',color: 'warning'}, '未发布');
              } else if (params.row.trainCoursePlanRelease == -1) {
                return h(resolveComponent('Tag'), {type: 'dot',color: 'error'}, '发布失败');
              }
            }
          },
          {
            title: '随堂测验', minWidth: 140,tooltip:true,resizable: true, render: (h, params) => {
              //  0：未开始，1：已完成，-1：进行中
              if (params.row.trainCoursePlanExam == 1) {
                return h(resolveComponent('Tag'), {type: 'dot',color: 'success'}, '已添加');
              } else {
                return h(resolveComponent('Tag'), {type: 'dot',color: 'default'}, '未添加');
              }
            }
          },
          {
            title: '培训人数', minWidth: 100,tooltip:true,resizable: true, render: (h, params) => {
              return h('span', params.row.trainCoursePlanFinishedNumber + '/' + params.row.trainCoursePlanTotalNumber + '人')
            }
          },
          {
            title: '培训时长', minWidth: 100,tooltip:true,resizable: true, render: (h, params) => {
              return h('span', params.row.trainCoursePlanTotalDuration + '分钟')
            }
          },
          {
            title: '完成状态', minWidth: 140,tooltip:true,resizable: true, render: (h, params) => {
              //  0：未开始，1：已完成，-1：进行中
              if (params.row.trainCoursePlanFinish == 1) {
                return h(resolveComponent('Tag'), {type: 'dot',color: 'success'}, '已完成');
              } else if (params.row.trainCoursePlanFinish == 2) {
                return h(resolveComponent('Tag'), {type: 'dot',color: 'warning'}, '进行中');
              } else if (params.row.trainCoursePlanFinish == 0) {
                return h(resolveComponent('Tag'), {type: 'dot',color: 'default'}, '未完成');
              }
            }
          },
          { title: '开始时间', minWidth: 100, key: 'trainCoursePlanBeginDate',tooltip:true,resizable: true },
          { title: '结束时间', minWidth: 100, key: 'trainCoursePlanEndDate',tooltip:true,resizable: true },

          {
            title: '操作', width: 120, fixed: 'right', render: (h, params) => {

              var operationButtons = [];
              operationButtons.push(
                  h('span', {
                    style: {"color": "#2d8cf0", "cursor": "pointer"},
                    onClick: () => {

                      state.selectData = JSON.parse(JSON.stringify(params.row));
                      state.formTitle = '列表';
                      state.formOperation = true;
                    }
                  }, "列表")
              )
              operationButtons.push(h(resolveComponent('Divider'), {type: 'vertical',}, ''))
              operationButtons.push(
                  h('span', {
                    style: {"color": "#2d8cf0", "cursor": "pointer"},
                    onClick: () => {


                      state.selectData = JSON.parse(JSON.stringify(params.row));
                      state.formTitle = '详情';
                      state.formOperation1 = true;

                      $axios.post(apiUrl.educateTrainPlanTrainCourseStudentPlanPrint,{trainPlanUuid:params.row.uuid}).then((res) => {
                        if (!!res.data) {
                          state.selectData = JSON.parse(JSON.stringify(params.row));
                          state.formTitle = '详情';
                          state.materialData = res.data.data
                          state.formOperation1 = true;
                        }
                      }).catch((err) => {
                        console.log("失败", err)
                      })
                    }
                  }, "详情")
              )
              return operationButtons;
            }
          }
        ],
        pagingParameters:{// 分页参数
          page:'pageNo',
          limit:'pageSize'
        },
        format: {//返回数据格式
          list: ['data'],//数据list
          count: ['count'],//数据总量
        },
      },
      trainingDirectionList:[],//培训方向
      carPlateColor:[
        {codeNumber: 1, color: 'primary', desc: '蓝色'},
        {codeNumber: 2, color: 'warning', desc: '黄色'},
        {codeNumber: 3, color: 'black', desc: '黑色'},
        {codeNumber: 4, color: ' ', desc: '白色'},
        {codeNumber: 5, color: 'success', desc: '绿色'},
        {codeNumber: 93, color: '#87d068', desc: '黄绿色'},
        {codeNumber: 9, color: 'cyan', desc: '其他'}
      ],//车辆颜色


      selectData:{},//选中数据
      formOperation:false,//弹框状态
      formOperation1:false,//弹框状态
      formTitle:'',//弹框标题

      materialData:{},//
    });


    //搜索方法
    const searchSubmit = ()=>{
      let formDataSearch = JSON.parse(JSON.stringify(state.formDataSearch));
      state.tableData.where = formDataSearch;
      wzTbale.value.tableLoadData(true)

    }


    //导出
    const exportData = ()=>{

      $ViewUIPlus.Modal.confirm({
        title: '导出提醒',
        content: '是否导出 全部 的安全教育培训信息?',
        onOk: () => {
          let data = JSON.parse(JSON.stringify(state.formDataSearch));
          data.areaLoc = !!data.areaLoc ? data.areaLoc.join("/") : '';

          $ViewUIPlus.Spin.show()
          $axios.post(apiUrl.educateTrainPlanTrainCoursePlanExport, data).then((res) => {
            $ViewUIPlus.Spin.hide()
            if (!!res) {
              window.open(apiUrl.export + res.data.data)
              $ViewUIPlus.Message.success('导出成功');
            }
          }).catch((err) => {
            $ViewUIPlus.Message.error('导出失败,请检查操作是否有误!');
            console.log("失败", err)
          })
        },
        onCancel: () => {
          //点击取消
        }
      })

      // console.log(wzTbale.value.tableDataSelected())

    }


    // 其他的生命周期
    onBeforeMount (() => {//beforeMount挂载前状态 // console.log("App ===> 相当于 vue2.x 中 beforeMount")

    })
    onMounted (async() => {//mounted 挂载结束状态  // console.log("App ===> 相当于 vue2.x 中 mounted")
      state.trainingDirectionList = await systemDictList({type: 'training_direction'})

    })

    // 注意，onBeforeUpdate 和 onUpdated 里面不要修改值
    onBeforeUpdate (() => {//beforeUpdate 更新前状态 // console.log("App ===> 相当于 vue2.x 中 beforeUpdate")

    })

    onUpdated (() => {//updated 更新完成状态 // console.log("App ===> 相当于 vue2.x 中 updated")

    })

    onBeforeUnmount (() => {//beforeDestroy 销毁前状态  // console.log("App ===> 相当于 vue2.x 中 beforeDestroy")
    })

    onUnmounted (() => {//destroyed 销毁完成状态  // console.log("App ===> 相当于 vue2.x 中 destroyed")
    })

    return {
      ...toRefs(state),
      searchSubmit,//搜索方法
      wzTbale,// ref 使用 封装的表格
      exportData,//导出
    }
  }
})


</script>
<style lang="less">
._wz_trainingRecords{
  padding: 10px;
  height: 100%;
  display: flex;
  flex-direction: column;

  .ivu-card-body {
    height: calc(100% - 51px);
  }
}
</style>
